package algorithm.tree.binarytree.deep;

import algorithm.tree.binarytree.base.TreeNode;
import algorithm.tree.binarytree.base.TreeNodeEvent;

import java.util.Stack;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Consumer;

public class ComputeTreeDeepNonRecursion {
    public static int getDeep(TreeNode node) {
        Stack<TreeNodeEvent<TreeNode>> nodeStack = new Stack<>();
        Stack<Integer> deepContext = new Stack<>();
        nodeStack.push(new TreeNodeEvent<>(0, node));
        while (!nodeStack.empty()) {
            TreeNodeEvent<TreeNode> event = nodeStack.pop();
            TreeNode temp = event.data();
            switch (event.type()) {
                case 0 -> {
                    if (temp == null) {
                        deepContext.push(0);
                    } else {
                        nodeStack.push(new TreeNodeEvent<>(3, null));
                        nodeStack.push(new TreeNodeEvent<>(0, temp.getLeft()));
                        nodeStack.push(new TreeNodeEvent<>(0, temp.getRight()));
                    }
                }
                case 3 -> {
                    int deep = Math.max(deepContext.pop(), deepContext.pop()) + 1;
                    deepContext.push(deep);
                }
            }
        }
        return deepContext.pop();
    }
}
